package com.zhiyizhen.handheld.common;

import java.security.MessageDigest;

/**
 * MD5转换工具类.
 */
public class MD5Util {

    private MD5Util() {
    }

    public static String md5MessageDigest(String s) {
        String md5MessageDigest = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(s.getBytes());
            md5MessageDigest = byteArr2HexStr(md.digest());
        } catch (Exception e) {
            LogUtil.e(e);
        }

        return md5MessageDigest;
    }

    private static String byteArr2HexStr(byte[] arrB) {
        int iLen = arrB.length;
        // 每个byte用两个字符才能表示，所以字符串的长度是数组长度的两倍
        StringBuilder sb = new StringBuilder(iLen * 2);
        for (int i = 0; i < iLen; i++) {
            int intTmp = arrB[i];
            // 把负数转换为正数
            while (intTmp < 0) {
                intTmp = intTmp + 256;
            }
            // 小于0F的数需要在前面补0
            if (intTmp < 16) {
                sb.append("0");
            }
            sb.append(Integer.toString(intTmp, 16));
        }
        return sb.toString();
    }

}
